package com.wxzz.elearing.pay.wx.mini;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;


public class GetWxOrderno {

	public String getPayNo(String url, String xmlParam) {
		DefaultHttpClient httpclient;
		httpclient = new DefaultHttpClient();
		httpclient = (DefaultHttpClient) HttpClientConnectionManager
				.getSSLInstance(httpclient);
		DefaultHttpClient client = new DefaultHttpClient();
		client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,
				true);
		HttpPost httpost = HttpClientConnectionManager.getPostMethod(url);
		String prepay_id = "";
		try {
			httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils
					.toString(response.getEntity(), "UTF-8");
			Map<String, Object> dataMap = new HashMap<String, Object>();
			//System.out.println(jsonStr);

			if (jsonStr.indexOf("FAIL") != -1) {
				return prepay_id;
			}
			Map map = doXMLParse(jsonStr);
			String return_code = (String) map.get("return_code");
			prepay_id = (String) map.get("prepay_id");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return prepay_id;
	}
	/**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 *
	 * @param strxml
	 * @return
	 */
	public static Map doXMLParse(String strxml) throws Exception {
		if (null == strxml || "".equals(strxml)) {
			return null;
		}

		Map m = new HashMap();
		InputStream in = String2Inputstream(strxml);
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if (children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = getChildrenText(children);
			}

			m.put(k, v);
		}

		// 关闭流
		in.close();

		return m;
	}

	/**
	 * 获取子结点的xml
	 *
	 * @param children
	 * @return String
	 */
	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator it = children.iterator();
			while (it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if (!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}

		return sb.toString();
	}

	public static InputStream String2Inputstream(String str) {
		return new ByteArrayInputStream(str.getBytes());
	}

	public String getRefund(String url, String xmlParam) {
		String res = "";
		try {
			CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(CertUtil.initCert()).build();
			HttpPost httpost = new HttpPost(url);
	        httpost.addHeader("Connection", "keep-alive");
	        httpost.addHeader("Accept", "*/*");
	        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	        httpost.addHeader("Host", "api.mch.weixin.qq.com");
	        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
	        httpost.addHeader("Cache-Control", "max-age=0");
	        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
	        httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
	        CloseableHttpResponse response = httpclient.execute(httpost);
	        String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
	        //System.out.println(jsonStr);
	        if(jsonStr.indexOf("<result_code><![CDATA[SUCCESS]]></result_code>")>=0&&jsonStr.indexOf("<return_code><![CDATA[SUCCESS]]></return_code>")>=0){
	        	String payment_no = "";
	        	int index1 = jsonStr.indexOf("<payment_no><![CDATA[");
    			int index2 = jsonStr.indexOf("]]></payment_no>");
    			if(index1>=0&&index2>=0){
    				payment_no = jsonStr.substring(index1+21, index2);
    			}
				res = payment_no+"success";
	        }else{
	        	int index1 = jsonStr.indexOf("<err_code_des><![CDATA[");
    			int index2 = jsonStr.indexOf("]]></err_code_des>");
    			if(index1>=0&&index2>=0){
    				res = jsonStr.substring(index1+23, index2);
    			}
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}

}
